<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Serve;

use App\Handlers\ImageUploadHandler;
use DB;
class JingPinController extends Controller
{
       // 检测用户是否登录，无登录跳转到登录页面
    public function __construct()
    {
       $this->middleware('auth');
    }
    //精品推荐首页展示
    public function index(){

        //取出所有精品推荐
        $jingpin = DB::table('serve_attach')->get();
        //取出所有精品附件
        $fujian = DB::table('jingpin_fujian')->get();

    	return view('staticpages.jingpin.index',compact('jingpin','fujian'));
    }

    //添加精品推荐
    public function create(){

        //取出所有服务
        $serve = Serve::get();

        return view('staticpages.jingpin.add',compact('serve'));
    }
    //获取精品表单数据
    public function store(Request $request,ImageUploadHandler $upload){

        $snum = DB::table('serve_attach')->count();

        if($snum >= 4){

            return '最多只能有4个精品推荐';exit;
        }

        //数据白名单
        $data = $request->only(['commit','price','is_price','sid']);

        //赋值服务id
        $data['sid'] = $request->id;
        //查出图片上传数量
        $num = count($request->fileimg);

        //判断图片数量是否小1或者大于3
        if($num >=1 && $num <= 3)
        {

            if(!in_array(null, $data))
            {
                //数据入库并返回状态
                 $status = DB::table('serve_attach')->insertGetId($data);

                 if($status)
                 {

                    //精品附件文件夹
                    $folder = 'jingpin';

                    //声明一个空数组
                    $s = array();
                    //编辑文件
                    foreach($request->fileimg as $fv){

                        //获取入库文件路径
                        $file = $upload->save($fv,$folder);

                       $s[] = DB::table('jingpin_fujian')->insert(['sid'=>$status,'img'=>$file['path']]);

                    }
                    //判断数组状态是否存在false
                    if(!in_array(false, $s)){

                        return redirect('app/jingpin');

                    }else{

                        return '录入文件失败';
                    }
                     

                 }else{

                    return '录入失败';
                 }

            }else{

                    return '请填写完整表单';
                }

        }else{

            return '请上传小于3张并且大于1张的图片';
        }    	
    }

    public function destroy(Request $request){

        $snum = DB::table('serve_attach')->count();

        if($snum <= 2){

            return '最少2个精品推荐';exit;
        }

        $status = DB::table('serve_attach')->where('id',$request->id)->delete();

        if($status){

            $sta = DB::table('jingpin_fujian')->where('sid',$request->id)->delete();

            if($sta){

                return back();

            }else{

                return '删除失败';
            }

        }else{

                return '删除失败';
        }

    }
}
